package dao;

import com.mysql.jdbc.Connection;
import util.DBUtil;
import model.User;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    //1. 根据userId查询对应的用户信息
    public User getUserById(int userId) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from user where userId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, userId);
            resultSet = statement.executeQuery();
            //查询结果只有1条或0条
            if(resultSet.next()) {
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPasswrod(resultSet.getString("password"));
                return user;
            }
        }catch (SQLException e) {
            throw new RuntimeException();
        } finally{
            DBUtil.close(connection,statement, resultSet);
        }
        return null;
    }

    //2.根据 username 来查询用户信息
    public User getUserByName(String username) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            String sql = "select * from user where username = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            resultSet = statement.executeQuery();
            //查询结果只有1条或0条
            if(resultSet.next()) {
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPasswrod(resultSet.getString("password"));
                return user;
            }
        }catch (SQLException e) {
            throw new RuntimeException();
        } finally{
            DBUtil.close(connection,statement, resultSet);
        }
        return null;
    }

}
